package com.msh.automatic.android.control.util.api

import android.util.Log
import cn.hutool.http.HttpGlobalConfig
import cn.hutool.http.HttpRequest
import cn.hutool.http.HttpUtil
import com.alibaba.fastjson2.JSON
import com.alibaba.fastjson2.JSONObject
import com.msh.automatic.android.control.util.ConfigUtil

object BaseApi {
    val BASE_URL="https://automatic-android-api.jobeyond.cn"

    fun post(api:String,params:Map<String, Any?>):Triple<String,String,JSONObject?>{
        var code = ""
        var message = ""
        for (i in 0..3) {
            try {
                val request = HttpRequest.post("$BASE_URL$api")
                    .timeout(HttpGlobalConfig.getTimeout())
                    .body(JSON.toJSONString(params))

                // 如果 token 不为空，添加 header
                ConfigUtil.getToken()?.let {
                    request.header("x-msh-token", it)
                }

                val res = request.execute().body()
                val json = JSONObject.parseObject(res)
                return Triple(json.getString("code")!!,json.getString("message")!!,json.getJSONObject("body"))
            }catch (e:Exception){
                code = "ERROR"
                message = e.message!!
                Log.e("HTTP","",e)
                val s = i+1L
                Thread.sleep(s*s*1000)
            }
        }
        return Triple(code,message,null)
    }
}